from CvPythonExtensions import *
from WriterUtils import *

import CvScreenEnums
import CvUtil
import CvConfigParser
import CvPath
import os
import os.path
import Popup as PyPopup
import shutil 

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# Change this to change the location where the resulting CIV4HandicapInfos.xml file 
# will be saved. So if the default value is left to "Test" then the 
# CIV4HandicapInfos.xml file would be written in a directory called "Test" inside 
# of the Tech Tree Editor mod folder.
# Default value is Test
g_strSaveDirectoryLocation = "Test"

# Change the value to false if the assets directory structure shouldn't be 
# created at the directory specified by the "Save Directory Location".
# Default value is True
g_bCreateAssetHierarchy = True

# Change the value to false if the changes made shouldn't be saved into the 
# assets directory for the tech editor. Changing it to false will require 
# manual copying of the saved files from the directory specified in the 
# "Save Directory Location" configurable option to the editor's asset directory 
# when wanting to edit existing mod files.
# Default value is True
g_bSaveChangesInEditorAssetsDirectory = True

def loadConfigurationValues():
	global g_strSaveDirectoryLocation
	global g_bCreateAssetHierarchy
	global g_bSaveChangesInEditorAssetsDirectory
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_strSaveDirectoryLocation = config.get("Tech Tree Editor", "Save Directory Location", "Test")
		g_bCreateAssetHierarchy = config.getboolean("Tech Tree Editor", "Create Asset Hierarchy", True)
		g_bSaveChangesInEditorAssetsDirectory = config.getboolean("Tech Tree Editor", "Save Changes In Editor Assets Directory", True)

		if(len(g_strSaveDirectoryLocation) == 0):
			g_strSaveDirectoryLocation = "Test"
			
class HandicapInfoWriter:
		
	def __init__(self):
		loadConfigurationValues()
		
	def freeTechsDefined(self, iHandicap):

		objHandicapInfo = gc.getHandicapInfo(iHandicap)

		for iI in range(gc.getNumTechInfos()):
			if(objHandicapInfo.isFreeTechs(iI)):
				return true

		return false
		
	def aifreeTechsDefined(self, iHandicap):

		objHandicapInfo = gc.getHandicapInfo(iHandicap)

		for iI in range(gc.getNumTechInfos()):
			if(objHandicapInfo.isAIFreeTechs(iI)):
				return true

		return false
		
		
	def printHandicap(self, iHandicap):
		
		objHandicapInfo = gc.getHandicapInfo(iHandicap)

		szText = ""
		
		szText = appendString(szText,"		<HandicapInfo>")
		
		szText = appendString(szText,"			<Type>%s</Type>" %(objHandicapInfo.getType()))
		szText = appendString(szText,"			<Description>%s</Description>" %(objHandicapInfo.getTextKey()))

		if(len(objHandicapInfo.getHelpKey()) > 0):
			szText = appendString(szText,"			<Help>%s</Help>" %(objHandicapInfo.getHelpKey()))
		else:
			szText = appendString(szText,"			<Help/>")

		szText = appendString(szText,"			<iFreeWinsVsBarbs>%s</iFreeWinsVsBarbs>" %(objHandicapInfo.getFreeWinsVsBarbs()))
		szText = appendString(szText,"			<iAnimalAttackProb>%s</iAnimalAttackProb>" %(objHandicapInfo.getAnimalAttackProb()))
		szText = appendString(szText,"			<iStartingLocPercent>%s</iStartingLocPercent>" %(objHandicapInfo.getStartingLocationPercent()))
		szText = appendString(szText,"			<iGold>%s</iGold>" %(objHandicapInfo.getStartingGold()))
		szText = appendString(szText,"			<iFreeUnits>%s</iFreeUnits>" %(objHandicapInfo.getFreeUnits()))
		szText = appendString(szText,"			<iUnitCostPercent>%s</iUnitCostPercent>" %(objHandicapInfo.getUnitCostPercent()))
		szText = appendString(szText,"			<iResearchPercent>%s</iResearchPercent>" %(objHandicapInfo.getResearchPercent()))
		szText = appendString(szText,"			<iDistanceMaintenancePercent>%s</iDistanceMaintenancePercent>" %(objHandicapInfo.getDistanceMaintenancePercent()))
		szText = appendString(szText,"			<iNumCitiesMaintenancePercent>%s</iNumCitiesMaintenancePercent>" %(objHandicapInfo.getNumCitiesMaintenancePercent()))
		szText = appendString(szText,"			<iMaxNumCitiesMaintenance>%s</iMaxNumCitiesMaintenance>" %(objHandicapInfo.getMaxNumCitiesMaintenance()))
		szText = appendString(szText,"			<iCivicUpkeepPercent>%s</iCivicUpkeepPercent>" %(objHandicapInfo.getCivicUpkeepPercent()))
		szText = appendString(szText,"			<iInflationPercent>%s</iInflationPercent>" %(objHandicapInfo.getInflationPercent()))
		szText = appendString(szText,"			<iHealthBonus>%s</iHealthBonus>" %(objHandicapInfo.getHealthBonus()))
		szText = appendString(szText,"			<iHappyBonus>%s</iHappyBonus>" %(objHandicapInfo.getHappyBonus()))
		szText = appendString(szText,"			<iAttitudeChange>%s</iAttitudeChange>" %(objHandicapInfo.getAttitudeChange()))
		szText = appendString(szText,"			<iNoTechTradeModifier>%s</iNoTechTradeModifier>" %(objHandicapInfo.getNoTechTradeModifier()))
		szText = appendString(szText,"			<iTechTradeKnownModifier>%s</iTechTradeKnownModifier>" %(objHandicapInfo.getTechTradeKnownModifier()))
		szText = appendString(szText,"			<iUnownedTilesPerGameAnimal>%s</iUnownedTilesPerGameAnimal>" %(objHandicapInfo.getUnownedTilesPerGameAnimal()))
		szText = appendString(szText,"			<iUnownedTilesPerBarbarianUnit>%s</iUnownedTilesPerBarbarianUnit>" %(objHandicapInfo.getUnownedTilesPerBarbarianUnit()))
		szText = appendString(szText,"			<iUnownedWaterTilesPerBarbarianUnit>%s</iUnownedWaterTilesPerBarbarianUnit>" %(objHandicapInfo.getUnownedWaterTilesPerBarbarianUnit()))
		szText = appendString(szText,"			<iUnownedTilesPerBarbarianCity>%s</iUnownedTilesPerBarbarianCity>" %(objHandicapInfo.getUnownedTilesPerBarbarianCity()))
		szText = appendString(szText,"			<iBarbarianCreationTurnsElapsed>%s</iBarbarianCreationTurnsElapsed>" %(objHandicapInfo.getBarbarianCreationTurnsElapsed()))
		szText = appendString(szText,"			<iBarbarianCityCreationTurnsElapsed>%s</iBarbarianCityCreationTurnsElapsed>" %(objHandicapInfo.getBarbarianCityCreationTurnsElapsed()))
		szText = appendString(szText,"			<iBarbarianCityCreationProb>%s</iBarbarianCityCreationProb>" %(objHandicapInfo.getBarbarianCityCreationProb()))
		szText = appendString(szText,"			<iAnimalBonus>%s</iAnimalBonus>" %(objHandicapInfo.getAnimalCombatModifier()))
		szText = appendString(szText,"			<iBarbarianBonus>%s</iBarbarianBonus>" %(objHandicapInfo.getBarbarianCombatModifier()))
		szText = appendString(szText,"			<iAIAnimalBonus>%s</iAIAnimalBonus>" %(objHandicapInfo.getAIAnimalCombatModifier()))
		szText = appendString(szText,"			<iAIBarbarianBonus>%s</iAIBarbarianBonus>" %(objHandicapInfo.getAIBarbarianCombatModifier()))
		szText = appendString(szText,"			<iStartingDefenseUnits>%s</iStartingDefenseUnits>" %(objHandicapInfo.getStartingDefenseUnits()))
		szText = appendString(szText,"			<iStartingWorkerUnits>%s</iStartingWorkerUnits>" %(objHandicapInfo.getStartingWorkerUnits()))
		szText = appendString(szText,"			<iStartingExploreUnits>%s</iStartingExploreUnits>" %(objHandicapInfo.getStartingExploreUnits()))
		szText = appendString(szText,"			<iAIStartingUnitMultiplier>%s</iAIStartingUnitMultiplier>" %(objHandicapInfo.getAIStartingUnitMultiplier()))
		szText = appendString(szText,"			<iAIStartingDefenseUnits>%s</iAIStartingDefenseUnits>" %(objHandicapInfo.getAIStartingDefenseUnits()))
		szText = appendString(szText,"			<iAIStartingWorkerUnits>%s</iAIStartingWorkerUnits>" %(objHandicapInfo.getAIStartingWorkerUnits()))
		szText = appendString(szText,"			<iAIStartingExploreUnits>%s</iAIStartingExploreUnits>" %(objHandicapInfo.getAIStartingExploreUnits()))
		szText = appendString(szText,"			<iBarbarianDefenders>%s</iBarbarianDefenders>" %(objHandicapInfo.getBarbarianInitialDefenders()))
		szText = appendString(szText,"			<iAIDeclareWarProb>%s</iAIDeclareWarProb>" %(objHandicapInfo.getAIDeclareWarProb()))
		szText = appendString(szText,"			<iAIWorkRateModifier>%s</iAIWorkRateModifier>" %(objHandicapInfo.getAIWorkRateModifier()))
		szText = appendString(szText,"			<iAIGrowthPercent>%s</iAIGrowthPercent>" %(objHandicapInfo.getAIGrowthPercent()))
		szText = appendString(szText,"			<iAITrainPercent>%s</iAITrainPercent>" %(objHandicapInfo.getAITrainPercent()))
		szText = appendString(szText,"			<iAIWorldTrainPercent>%s</iAIWorldTrainPercent>" %(objHandicapInfo.getAIWorldTrainPercent()))
		szText = appendString(szText,"			<iAIConstructPercent>%s</iAIConstructPercent>" %(objHandicapInfo.getAIConstructPercent()))
		szText = appendString(szText,"			<iAIWorldConstructPercent>%s</iAIWorldConstructPercent>" %(objHandicapInfo.getAIWorldConstructPercent()))
		szText = appendString(szText,"			<iAICreatePercent>%s</iAICreatePercent>" %(objHandicapInfo.getAICreatePercent()))
		szText = appendString(szText,"			<iAIWorldCreatePercent>%s</iAIWorldCreatePercent>" %(objHandicapInfo.getAIWorldCreatePercent()))
		szText = appendString(szText,"			<iAICivicUpkeepPercent>%s</iAICivicUpkeepPercent>" %(objHandicapInfo.getAICivicUpkeepPercent()))
		szText = appendString(szText,"			<iAIUnitCostPercent>%s</iAIUnitCostPercent>" %(objHandicapInfo.getAIUnitCostPercent()))
		szText = appendString(szText,"			<iAIUnitSupplyPercent>%s</iAIUnitSupplyPercent>" %(objHandicapInfo.getAIUnitSupplyPercent()))
		szText = appendString(szText,"			<iAIUnitUpgradePercent>%s</iAIUnitUpgradePercent>" %(objHandicapInfo.getAIUnitUpgradePercent()))
		szText = appendString(szText,"			<iAIInflationPercent>%s</iAIInflationPercent>" %(objHandicapInfo.getAIInflationPercent()))
		szText = appendString(szText,"			<iAIWarWearinessPercent>%s</iAIWarWearinessPercent>" %(objHandicapInfo.getAIWarWearinessPercent()))
		szText = appendString(szText,"			<iAIPerEraModifier>%s</iAIPerEraModifier>" %(objHandicapInfo.getAIPerEraModifier()))

		if(objHandicapInfo.getNumGoodies() > 0):
			szText = appendString(szText,"			<Goodies>")
			for iI in range(objHandicapInfo.getNumGoodies()):
				szText = appendString(szText,"				<GoodyType>%s</GoodyType>" %(gc.getGoodyInfo(objHandicapInfo.getGoodies(iI)).getType()))

			szText = appendString(szText,"			</Goodies>")
		else:
			szText = appendString(szText,"			<Goodies/>")

		if(self.freeTechsDefined(iHandicap)):
			szText = appendString(szText,"			<FreeTechs>")
			for iI in range(gc.getNumTechInfos()):
				if(objHandicapInfo.isFreeTechs(iI)):
					szText = appendString(szText,"				<FreeTech>")
					szText = appendString(szText,"					<TechType>%s</TechType>" %(gc.getTechInfo(iI).getType()))
					szText = appendString(szText,"					<bFreeTech>1</bFreeTech>")
					szText = appendString(szText,"				</FreeTech>")
								
			szText = appendString(szText,"			</FreeTechs>")
		else:
			szText = appendString(szText,"			<FreeTechs/>")

		if(self.aifreeTechsDefined(iHandicap)):
			szText = appendString(szText,"			<AIFreeTechs>")
			for iI in range(gc.getNumTechInfos()):
				if(objHandicapInfo.isAIFreeTechs(iI)):
					szText = appendString(szText,"				<FreeTech>")
					szText = appendString(szText,"					<TechType>%s</TechType>" %(gc.getTechInfo(iI).getType()))
					szText = appendString(szText,"					<bFreeTech>1</bFreeTech>")
					szText = appendString(szText,"				</FreeTech>")
								
			szText = appendString(szText,"			</AIFreeTechs>")
		else:
			szText = appendString(szText,"			<AIFreeTechs/>")
		
				
		szText = appendString(szText,"		</HandicapInfo>")
			
		return szText

						
	def printHandicaps(self):	
	
		strSavePath = ""
		strFileSavePath = ""
		strModPath = ""
		strModAssetPath = ""
		strModAssetSavePath = ""
		strModAssetPath = ""
		
		if(os.access(CvPath.userActiveModDir,os.F_OK)):
			strModPath = CvPath.userActiveModDir
		elif(os.access(CvPath.installActiveModDir,os.F_OK)):
			strModPath = CvPath.installActiveModDir
		else:
			self.dataSavePopup(false)
			return
			
		strSavePath = "%s\%s" %(strModPath,g_strSaveDirectoryLocation)
		strModAssetPath = "%s\\Assets\\" %(strModPath)
		
		if(g_bCreateAssetHierarchy):
			strSavePath += "\Assets\XML\GameInfo" 

		strFileSavePath = "%s\%s" %(strSavePath, "CIV4HandicapInfo.xml")

		try:
			if(os.access(strSavePath,os.F_OK)):
				if(os.access(strFileSavePath,os.F_OK)):
					os.remove(strFileSavePath)
				os.removedirs(strSavePath)
		except:
			pass
			
		if(not os.access(strSavePath,os.F_OK)):
			os.makedirs(strSavePath)

							
		szText = "<?xml version=\"1.0\"?>"
		szText = appendString(szText,"<!-- Created by Tech Civilizeditor %s by TheLopez-->" %(editorVersion()))
		szText = appendString(szText,"<!-- Sid Meier's Civilization 4 -->")
		szText = appendString(szText,"<!-- Copyright Firaxis Games 2005 -->")
		szText = appendString(szText,"<!-- -->")
		szText = appendString(szText,"<!-- Handicap Infos -->")
		szText = appendString(szText,"<Civ4HandicapInfo xmlns=\"x-schema:CIV4GameInfoSchema.xml\">")
		szText = appendString(szText,"	<HandicapInfos>")
				
		for iHandicap in range(gc.getNumHandicapInfos()):

			if(gc.getHandicapInfo(iHandicap).isDeleted()):
				continue

			szText = appendString(szText,self.printHandicap(iHandicap))
			
						
		szText = appendString(szText,"	</HandicapInfos>")
		szText = appendString(szText,"</Civ4HandicapInfo>")

			
		fd = os.open(strFileSavePath, os.O_CREAT)
		os.close(fd)

		fd = os.open(strFileSavePath, os.O_RDWR)
		os.write(fd, szText)
		os.close(fd)
		
		if(g_bSaveChangesInEditorAssetsDirectory):
			strModAssetPath = "%s\%s" %(strModPath,"\Assets\XML\GameInfo")
			strModAssetSavePath = "%s\%s" %(strModPath, "\Assets\XML\GameInfo\CIV4HandicapInfo.xml")
			try:
				if(os.access(strModAssetPath,os.F_OK)):
					if(os.access(strModAssetSavePath,os.F_OK)):
						os.remove(strModAssetSavePath)
			except:
				pass
			
			if(not os.access(strModAssetPath,os.F_OK)):
				os.makedirs(strModAssetPath)

			fd = os.open(strModAssetSavePath, os.O_CREAT)
			os.close(fd)

			fd = os.open(strModAssetSavePath, os.O_RDWR)
			os.write(fd, szText)
			os.close(fd)
	

